package cn.bearspark.like.provider.dao.buffer;

import cn.bearspark.framework.redis.starter.buffer.zset.RedisZSetBuffer;
import cn.bearspark.like.provider.dao.key.HappeningLikeBufferKeyBuilder;
import cn.bearspark.like.provider.dao.mapper.HappeningLikeMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

/**
 * 动态点赞的 ZSet 的缓存器
 *
 * @author f
 */
@Component
public class HappeningLikeZSetBuffer extends RedisZSetBuffer {

    private final HappeningLikeMapper happeningLikeMapper;

    private final HappeningLikeBufferKeyBuilder happeningLikeBufferKeyBuilder;

    public HappeningLikeZSetBuffer(RedisTemplate<String, Object> redisTemplate,
                                   HappeningLikeMapper happeningLikeMapper,
                                   HappeningLikeBufferKeyBuilder happeningLikeBufferKeyBuilder) {
        super(redisTemplate);
        this.happeningLikeMapper = happeningLikeMapper;
        this.happeningLikeBufferKeyBuilder = happeningLikeBufferKeyBuilder;
    }

    /**
     * 从指定的动态 id List 集合中，过滤出指定用户点赞过的动态 id Set 集合
     *
     * @param happeningIdList 指定的动态 id List 集合
     * @param userId          指定的用户 id
     * @return 过滤出的指定用户点赞过的动态 id Set 集合
     */
    public Set<Long> filter(List<Long> happeningIdList, long userId) {
        return super.filter(
                happeningLikeBufferKeyBuilder.buildUserLikeZSetKey(userId),
                happeningIdList,
                missingHappeningIdList -> happeningLikeMapper.getLikedHappeningIdSet(missingHappeningIdList, userId)
        );
    }

    /**
     * 判断指定动态是否被指定用户点赞
     *
     * @param happeningId 指定的动态 id
     * @param userId      指定的用户 id
     * @return 指定动态是否被指定用户点赞
     */
    public boolean exists(long happeningId, long userId) {
        return super.exists(
                happeningLikeBufferKeyBuilder.buildUserLikeZSetKey(userId),
                happeningId,
                () -> happeningLikeMapper.countHappeningLiked(happeningId, userId)
        );
    }

    /**
     * 清理指定用户点赞指定动态的缓存
     *
     * @param happeningId 指定的动态 id
     * @param userId      指定的用户 id
     */
    public void clean(long happeningId, long userId) {
        super.clean(happeningLikeBufferKeyBuilder.buildUserLikeZSetKey(userId), happeningId);
    }
}
